﻿/**
*    @file:    servicecontrolthread.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2025-04-07  18:00
*/
#include "servicecontrolthread.h"

#include <QApplication>
#include <QDebug>
#include <QTimer>
#include <qglobalconfig.h>

ServiceControlThread::ServiceControlThread(QObject *parent)
    : QThread(parent)
{
    moveToThread(this);
    start();
}

ServiceControlThread::~ServiceControlThread()
{
    quit();
    wait();
}

void ServiceControlThread::slot_installService()
{
    qDebug() << __FUNCTION__;
    QString serverName = QGlobalConfig::getInstance().read("serviceManage", "serverName", "").toString();
    QString serverDescription = QGlobalConfig::getInstance().read("serviceManage", "serverDescription", "").toString();
    QString serverPath = QApplication::applicationDirPath() + "/" + QGlobalConfig::getInstance().read("serviceManage", "serverPath", "").toString();

    deviceOperator.InstallServiceInterface(serverName.toStdString().c_str(),
                                           serverDescription.toStdWString().data(),
                                           serverPath.toStdString().c_str());
}

void ServiceControlThread::slot_uninstallService()
{
    QString serverName = QGlobalConfig::getInstance().read("serviceManage", "serverName", "").toString();
    deviceOperator.UninstallServiceInterface(serverName.toStdString().c_str());
}

void ServiceControlThread::slot_startService()
{
    QString serverName = QGlobalConfig::getInstance().read("serviceManage", "serverName", "").toString();
    deviceOperator.StartServiceInterface(serverName.toStdString().c_str());
}

void ServiceControlThread::slot_stopService()
{
    QString serverName = QGlobalConfig::getInstance().read("serviceManage", "serverName", "").toString();
    deviceOperator.StopServiceInterface(serverName.toStdString().c_str());
}

void ServiceControlThread::slot_getServiceState()
{
    QString serverName = QGlobalConfig::getInstance().read("serviceManage", "serverName", "").toString();
    QString serverPath = QGlobalConfig::getInstance().read("serviceManage", "serverPath", "").toString();
    if (serverName.isEmpty())
    {
        signal_serviceState(-2, "服务名称不可为空!");
        return;
    }
    if (serverPath.isEmpty())
    {
        signal_serviceState(-2, "服务路径不可为空!");
        return;
    }
    int serverState = deviceOperator.getServiceState(serverName.toStdString().c_str());
    signal_serviceState(serverState, serverState == SERVICE_RUNNING ? "运行" : "停止");
}

void ServiceControlThread::run()
{
    QTimer timer;
    connect(&timer, &QTimer::timeout, this, &ServiceControlThread::slot_getServiceState);
    timer.start(1500);
    exec();
    timer.stop();
}
